package pdfsetter.core.schema;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import pdfsetter.core.util.RandomAccessIterable;
import pdfsetter.core.util.RandomAccessIterableIterator;

/**
 * This is {@link FillingSchema} in which all selections are fixed - it stores list with selections and just returns selection from asked position.
 * 
 * @author Andrzej Dorobisz
 */
public class FixedFillingSchema implements FillingSchema {

    int expectedNumberOfFiles;
    List<PageSelection> pageSelections;

    /*
     * While constructing object given list with selections is copied to own list. During this process maximum file number is calculated - in this way the
     * expected number of files is automatically set. We assume that file numbers and page numbers are counted from zero.
     */
    public FixedFillingSchema(List<PageSelection> pageSelectionsList) {
        int maxFileNumber = -1;
        pageSelections = new ArrayList<PageSelection>(pageSelectionsList.size());
        for (PageSelection selection : pageSelectionsList) {
            if (selection.getFileNumber() > maxFileNumber)
                maxFileNumber = selection.getFileNumber();
            pageSelections.add(selection);
        }
        expectedNumberOfFiles = maxFileNumber + 1;
    }

    @Override
    public RandomAccessIterable<PageSelection> getPageSelections() {
        return new RandomAccessIterable<PageSelection>() {

            @Override
            public Iterator<PageSelection> iterator() {
                return new RandomAccessIterableIterator<PageSelection>(this);
            }

            @Override
            public PageSelection get(int index) {
                return pageSelections.get(index);
            }

            @Override
            public int size() {
                return pageSelections.size();
            }
        };
    }

    @Override
    public int getExpectedNumberOfFiles() {
        return expectedNumberOfFiles;
    }
}
